using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using System;

namespace Babylon.Toolbox
{
    public partial class StatesManager : IDisposable
    {
        static Dictionary<GraphicsDevice, StatesManager> managers = new Dictionary<GraphicsDevice, StatesManager>();
        
        GraphicsDevice device;

        public static StatesManager FromDevice(GraphicsDevice graphicsDevice)
        {
            StatesManager statesManager;

            if (!managers.TryGetValue(graphicsDevice, out statesManager))
            {
                statesManager = new StatesManager(graphicsDevice);
                managers.Add(graphicsDevice, statesManager);
            }

            return statesManager;
        }

        private StatesManager(GraphicsDevice device)
        {
            this.device = device;
            for (int index = 0; index < 8; index++)
            {
                uAddressMode[index] = TextureAddressMode.Wrap;
                vAddressMode[index] = TextureAddressMode.Wrap;
            }

            Reset();
        }

        public GraphicsDevice Device
        {
            get { return device; }
            // added to be able to load it on UI thread and apply it on compositer thread
            set { device = value; }
        }

        public void Reset()
        {
            currentRasterizerKey = -1;
            currentDepthStencilKey = -1;
            for (int index = 0; index < 8; index++)
            {
                currentSamplerKey[index] = -1;
                ApplySamplerState(index);
            }
            ApplyRasterizerState();
            ApplyDepthStencilState();
            ApplyBlendState();
        }

        public void Dispose()
        {
            rasterizerStates.Clear();

            depthStencilStates.Clear();
        }
    }
}
